import { Form, Table } from 'antd';
import Cls from 'classnames';
import { ContractManageAPI } from '../common/type';
import { useContext, useEffect, useMemo, useState } from 'react';
import { getKeyNodesTableConfig, handListMoment } from '../mconfig';
import { getKeyRouter, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { ConractControllerContext, IContractsActionEnum } from '../common';

export const UpdatePaymentView: React.FC<ContractManageAPI.IUpdatePaymentView> = ({ selectPaymentType, formName }) => {
  /** 获取上下文 */
  const { pageType, contractDetailInfo, contarctJsonList, contractForm, oldContractInfo, contractDispatch, locationState } =
    useContext(ConractControllerContext);

  /** 保存付款信息 */
  const [paymentDataSource, setPaymentDataSource] = useState<Record<string, any>[]>([]);

  /** 初始化 */
  useEffect(() => {
    if (selectPaymentType || selectPaymentType == null) {
      defauTableDataSource();
    }
  }, [selectPaymentType]);

  /** 数据改变 */
  useEffect(() => {
    if (pageType == 'modify') {
      if (paymentDataSource?.length > 0) {
        formName?.setFieldsValue({
          processList: paymentDataSource,
        });
      }
    } else {
      formName?.setFieldsValue({
        processList: paymentDataSource,
      });
    }
  }, [paymentDataSource]);

  /** 详情初始化 */
  useEffect(() => {
    if (contractDetailInfo?.id) {
      const processList: Record<string, any>[] = handListMoment(contractDetailInfo?.processList, ['payTime'], false);
      setPaymentDataSource(processList);
    }
  }, [contractDetailInfo?.processList?.length]);

  /** 初始化付款信息 */
  const defauTableDataSource = () => {
    const contractAllNum: number = formName?.getFieldValue('sumInTax') ? formName?.getFieldValue('sumInTax') : 0;
    const capitalDir: number = formName?.getFieldValue('capitalDir') ? formName?.getFieldValue('capitalDir') : 0;
    if (selectPaymentType == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1000`) {
      const payConfig = [
        {
          key: `processnode-${getKeyRouter()}`,
          payType: 0,
          payNum: 100,
          modifyFlag: 0,
          paySum: contractAllNum,
          payResidueSum: contractAllNum,
          payState: '0',
          payFlag: 1,
        },
      ];
      setPaymentDataSource(payConfig);
    } else if (selectPaymentType == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1001`) {
      const payConfig = [
        {
          key: `processnode-${getKeyRouter()}`,
          payType: 1,
          modifyFlag: 0,
          payNum: 10,
          paySum: (contractAllNum * 10) / 100,
          payResidueSum: (contractAllNum * 10) / 100,
          payState: '0',
          payFlag: 1,
        },
        {
          key: `processnode-${getKeyRouter()}`,
          payType: 2,
          modifyFlag: 0,
          payNum: 60,
          paySum: (contractAllNum * 60) / 100,
          payResidueSum: (contractAllNum * 60) / 100,
          payState: '0',
          payFlag: 1,
        },
        {
          key: `processnode-${getKeyRouter()}`,
          payType: 2,
          modifyFlag: 0,
          payNum: 25,
          paySum: (contractAllNum * 25) / 100,
          payResidueSum: (contractAllNum * 25) / 100,
          payState: '0',
          payFlag: 1,
        },
        {
          key: `processnode-${getKeyRouter()}`,
          payType: 3,
          modifyFlag: 0,
          payNum: 5,
          paySum: (contractAllNum * 5) / 100,
          payResidueSum: (contractAllNum * 5) / 100,
          payState: '0',
          payFlag: 1,
        },
      ];
      setPaymentDataSource(payConfig);
    } else if (selectPaymentType == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002` && capitalDir != 2) {
      const payConfig = [
        {
          key: `processnode-${getKeyRouter()}`,
          payType: 4,
          modifyFlag: 0,
          payNum: 100,
          paySum: 0,
          payResidueSum: 0,
          payFlag: 1,
          payState: '0',
        },
      ];
      setPaymentDataSource(payConfig);
    } else if (selectPaymentType == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002` && capitalDir == 2) {
      const payConfig = [
        {
          key: `processnode-${getKeyRouter()}`,
          payType: 4,
          modifyFlag: 0,
          payNum: 0,
          paySum: 0,
          payResidueSum: 0,
          payFlag: 0,
          payState: '0',
        },
      ];
      setPaymentDataSource(payConfig);
    } else {
      setPaymentDataSource([]);
    }

    let oldProcessList = contractDetailInfo?.processList ? [...contractDetailInfo?.processList] : [];
    if (oldProcessList && oldProcessList.length) {
      oldProcessList.map((item) => {
        item.modifyFlag = 2;
      });
    }

    contractDispatch({
      type: IContractsActionEnum.CONTRACT_JSONLIST,
      payload: {
        ...contarctJsonList,
        processList: oldProcessList,
      },
    });
  };

  /** 处理添加进度款 */
  const handleAddProgress = () => {
    let addItemObj: Record<string, any> = {
      key: `processnode-${getKeyRouter()}`,
      payType: 5,
      modifyFlag: 0,
      payFlag: 0,
      payNum: 0,
      paySum: 0,
      payState: '0',
    };
    const payStyle = formName?.getFieldValue('payStyle');
    const capitalDir: number = formName?.getFieldValue('capitalDir') ? formName?.getFieldValue('capitalDir') : 0;

    if (payStyle == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002` && capitalDir == 2) {
      addItemObj = {
        key: `processnode-${getKeyRouter()}`,
        payType: 4,
        modifyFlag: 0,
        payNum: 0,
        paySum: 0,
        payResidueSum: 0,
        payFlag: 0,
        payState: '0',
      };
    } else if (payStyle == `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}1002` && capitalDir != 2) {
      addItemObj = {
        key: `processnode-${getKeyRouter()}`,
        payType: 4,
        modifyFlag: 0,
        payNum: 100,
        paySum: 0,
        payResidueSum: 0,
        payFlag: 1,
        payState: '0',
      };
    }

    let changeList: Record<string, any>[] = contarctJsonList?.['processList']?.length > 0 ? contarctJsonList?.['processList'] : [];
    changeList?.push(addItemObj);
    contractDispatch({
      type: IContractsActionEnum.CONTRACT_JSONLIST,
      payload: {
        ...contarctJsonList,
        processList: changeList,
      },
    });

    const formProcessList: Record<string, any>[] = formName?.getFieldValue('processList');
    const nowTable: Record<string, any>[] = formProcessList && formProcessList?.length > 0 ? formProcessList : [];
    let copyTableConfig: Record<string, any>[] = [...nowTable];
    // copyTableConfig.splice(-1, 0, addItemObj); //指定进度款位置
    copyTableConfig.push(addItemObj);
    setPaymentDataSource(copyTableConfig);
  };

  /** 删除添加的进度款 */
  const delProgressPay = (delRes: Record<string, any>) => {
    let newChangeList: Record<string, any>[] = [];
    const changeList: Record<string, any>[] = contarctJsonList?.['processList']?.length > 0 ? contarctJsonList?.['processList'] : [];
    if (delRes && delRes?.id) {
      const delObj: Record<string, any> = {
        ...delRes,
        modifyFlag: '2',
      };
      newChangeList = changeList?.filter((item: any) => item?.id != delObj?.id);
      newChangeList?.push(delObj);
    } else if (delRes && delRes?.key) {
      newChangeList = changeList?.filter((item: any) => item?.key != delRes?.key);
    }
    contractDispatch({
      type: IContractsActionEnum.CONTRACT_JSONLIST,
      payload: {
        ...contarctJsonList,
        processList: newChangeList,
      },
    });

    const newPayList: Record<string, any>[] = contractForm?.getFieldValue('processList');
    const delPayList: Record<string, any>[] = newPayList?.filter((item: any) => {
      if (item?.id) {
        return item?.id != delRes?.id;
      } else {
        return item?.key != delRes?.key;
      }
    });
    setPaymentDataSource(delPayList);
  };

  /** 返回表格配置 */
  const columnsMemo = useMemo(() => {
    return getKeyNodesTableConfig(
      //关键节点
      selectPaymentType || contractDetailInfo?.payStyle || oldContractInfo?.payStyle,
      handleAddProgress,
      delProgressPay,
      formName,
      pageType,
      locationState,
    );
  }, [selectPaymentType, formName, contractDetailInfo?.payStyle, oldContractInfo?.payStyle, contarctJsonList, paymentDataSource]);

  return (
    <div className={Cls('list-table', 'descriptionsType-tableSty', 'descriptionsType-tableFormSty')}>
      <Form.Item name="processList" valuePropName="dataSource">
        <Table
          columns={columnsMemo}
          bordered
          size="small"
          dataSource={paymentDataSource}
          rowKey={(res) => (res?.id ? res?.id : res?.key)}
          scroll={{ x: 1200, y: '' }}
          pagination={false}
        />
      </Form.Item>
    </div>
  );
};
